package com.ewanghuiju.app.di.module;

import android.text.TextUtils;
import android.util.Log;

import com.ewanghuiju.app.BuildConfig;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.di.qualifier.MyTestUrl;
import com.ewanghuiju.app.di.qualifier.MyUrl;
import com.ewanghuiju.app.di.qualifier.ZhihuUrl;
import com.ewanghuiju.app.model.http.api.MyApis;
import com.ewanghuiju.app.model.http.api.MyTestApis;
import com.ewanghuiju.app.model.http.api.OldServerApis;
import com.ewanghuiju.app.model.prefs.ImplPreferencesHelper;
import com.ewanghuiju.app.util.LogUtil;
import com.ewanghuiju.app.util.SystemUtil;
import com.kingbogo.logview.LogView;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author sj  qq:751943509
 * @class describe
 * @time 2020/2/10
 */
@Module
public class HttpModule {

    @Singleton
    @Provides
    Retrofit.Builder provideRetrofitBuilder() {
        return new Retrofit.Builder();
    }


    @Singleton
    @Provides
    OkHttpClient.Builder provideOkHttpBuilder() {
        return new OkHttpClient.Builder();
    }

    @Singleton
    @Provides
    @ZhihuUrl
    Retrofit provideZhihuRetrofit(Retrofit.Builder builder, OkHttpClient client) {
        return createRetrofit(builder, client, OldServerApis.HOST);
    }

    @Singleton
    @Provides
    @MyTestUrl
    Retrofit provideGoldRetrofit(Retrofit.Builder builder, OkHttpClient client) {
        return createRetrofit(builder, client, MyTestApis.HOST);
    }

    @Singleton
    @Provides
    @MyUrl
    Retrofit provideMyRetrofit(Retrofit.Builder builder, OkHttpClient client) {
        return createRetrofit(builder, client, MyApis.HOST);
    }

    @Singleton
    @Provides
    OkHttpClient provideClient(OkHttpClient.Builder builder) {
        if (Constants.IS_DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    try {
                        String text = URLDecoder.decode(message, "utf-8");
                        LogView.getInstance().addLog("e网惠聚数据",text);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogView.getInstance().setTipsInfo(message);
                    }
                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
        File cacheFile = new File(Constants.PATH_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!SystemUtil.isNetworkConnected()) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                if (SystemUtil.isNetworkConnected()) {
                    int maxAge = 0;
                    // 有网络时, 不缓存, 最大保存时长为0
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    // 无网络时，设置超时为4周
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };

        Interceptor apikey = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                ImplPreferencesHelper mImplPreferencesHelper = App.getAppComponent().preferencesHelper();
                String token = mImplPreferencesHelper.getToken();
//                LogUtil.i("用户token:" + token);
                Request request = chain.request();
                request = request.newBuilder()
                        .addHeader("Content-Type", "application/json;charset=utf-8")
                        .addHeader("token", TextUtils.isEmpty(token) ? "" : token)
                        .build();
                return chain.proceed(request);
            }
        };
//        设置统一的请求头部参数
        builder.addInterceptor(apikey);
        //设置缓存
        builder.addNetworkInterceptor(cacheInterceptor);
        builder.addInterceptor(cacheInterceptor);
        builder.cache(cache);
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
//        builder.connectTimeout(20 * 1000, TimeUnit.MILLISECONDS);
//        builder.readTimeout(20 * 1000, TimeUnit.MILLISECONDS);
//        builder.writeTimeout(20 * 1000, TimeUnit.MILLISECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        return builder.build();
    }

    @Singleton
    @Provides
    OldServerApis provideZhihuService(@ZhihuUrl Retrofit retrofit) {
        return retrofit.create(OldServerApis.class);
    }

    @Singleton
    @Provides
    MyTestApis provideGoldService(@MyTestUrl Retrofit retrofit) {
        return retrofit.create(MyTestApis.class);
    }

    @Singleton
    @Provides
    MyApis provideMyService(@MyUrl Retrofit retrofit) {
        return retrofit.create(MyApis.class);
    }

    private Retrofit createRetrofit(Retrofit.Builder builder, OkHttpClient client, String url) {
        return builder
                .baseUrl(url)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .addConverterFactory(CustomizeGsonConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}
